//
//  GestureViewController.m
//  NiuBanJinGold
//
//  Created by zf on 15/10/13.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "GestureViewController.h"
#import "CoreArchive.h"
#import "CoreLockConst.h"
#import "User.h"

@interface GestureViewController ()<UITableViewDelegate , UITableViewDataSource>
@property (nonatomic , strong) UISwitch *switch_gesture;
@end

@implementation GestureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self.navigationItem setTitle:@"手势密码管理"];
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    
    [tableView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    
    
    UIView *view_footView = [[UIView alloc]initWithFrame:CGRectZero];
    [tableView setTableFooterView:view_footView];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    tableView.backgroundColor = BASECOLOR;
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeGestureAction)];
    [self.view addGestureRecognizer:swipeGesture];
    
}


#pragma mark -swipeGestureAction
-(void)swipeGestureAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellId = @"cellID";
    tableView.rowHeight = MULTIPLYHEIGHT(100.0 / 2);
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (nil == cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
           }
    cell.textLabel.font = [UIFont systemFontOfSize:15.0];
    cell.textLabel.textColor = [UsefulUtil colorWithHexString:@"#434343"];
    if (indexPath.section == 0) {
        cell.textLabel.text =@"手势密码";
        
        //开关
        self.switch_gesture = [[UISwitch alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - MULTIPLYWIDTH(140.0 / 2), MULTIPLYHEIGHT(5), MULTIPLYWIDTH(100), 30)];
        [cell.contentView addSubview:self.switch_gesture];
    
        [self.switch_gesture addTarget:self action:@selector(defaults:) forControlEvents:UIControlEventValueChanged ];
        
        // 默认设置为开启
        // 如果读出来的值和保存的值不一样,那么就以读出来的值为准
        
        NSString *value =  [[NSUserDefaults standardUserDefaults]valueForKey:@"gesturePasswordEnabled"];
        
        if (!value) { //表明用户是第一次进来设置，那么设置默认为开
            
            self.switch_gesture.on = YES;
        } else { //有值了
            
            [value isEqualToString:@"1"]? (self.switch_gesture.on = YES) : (self.switch_gesture.on = NO);

        }
    }
    
    if (indexPath.section == 1) {
        
        cell.textLabel.text =@"修改手势密码";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//箭头
    }
    return cell;
    
}
-(void) defaults :(UISwitch *) switch_gesture {
    
    if (switch_gesture.on) { // 用户打开密码，key 值为1,OR key 值为2
        
        [[NSUserDefaults standardUserDefaults ] setValue:@"1" forKey:@"gesturePasswordEnabled"];
    }else {
        
         [[NSUserDefaults standardUserDefaults ] setValue:@"2" forKey:@"gesturePasswordEnabled"];
    }
    [[NSUserDefaults standardUserDefaults ] synchronize];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    CGFloat height = 0.0 ;
    if (section == 0) {
        height = MULTIPLYHEIGHT(40.0 / 2) ;
    }
    if (section == 1) {
        height = MULTIPLYHEIGHT(40.0 / 2);
        
    }
    
    return height;
}
#pragma mark -didSelectRowAtIndexPath

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        //读取
        BOOL switch_on=[defaults boolForKey:@"gesturePasswordEnabled"];
        self.switch_gesture.on = switch_on ;
    }
    
    if (indexPath.section == 1) { //重置手势密码
      
        [self gesturePWD];
        
            }
}

- (void)gesturePWD {
    
    [CLLockVC showModifyLockVCInVC:self successBlock:^(CLLockVC *lockVC, NSString *pwd) {
        
        NSString *pwdLocal = [CoreArchive strForKey:@"旧密码"];
        
        NSLog(@"%@" , GETCURRENTUSERINOBYPRAMETERES(user_userName));
        
        NSDictionary *dic_parames = @{@"mobile":GETCURRENTUSERINOBYPRAMETERES(user_userName),@"oldGesturePassword":pwdLocal,@"newGesturePassword":pwd,@"channel":@"appstore"};
        
        [MBProgressHUD showHUDAddedTo:lockVC.view animated:YES]; //进度条
        
        [[NetworkUtil sharedNetworkUtil] zzjrUserResetGesturePasswordByParmeteres:dic_parames transferResultUsingBlock:^(id parsedData, NSError *error) {
            
            if (!error) {  //没有网络错误
                
                [MBProgressHUD hideAllHUDsForView:lockVC.view animated:YES];
                // 开始解析数据
                NSDictionary *dic = parsedData;
                
                if([dic[@"status"] intValue] == 0) {
                    
                    // 保存用户重要信息
                    
                    User *user = [[UserManager sharedUserManager] getCurrentUser];
                    user.user_userToken = dic[@"result"][@"token"];
                    [[UserManager sharedUserManager] saveCurrentUser:user];
                    
                    [lockVC dismiss:0];
                } else {// 不是网络出错, 其它错误
                    
                    [MBProgressHUD hideAllHUDsForView:lockVC.view animated:YES];
                    [lockVC.view setUserInteractionEnabled:YES];
                    
                    UIAlertView *alert_reset = [[UIAlertView alloc] initWithTitle:dic[@"msg"] message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"重设", nil];
                    
                    [alert_reset show];
                    
                    [lockVC dismiss:0];

                }
            }else {
                
                [MBProgressHUD hideAllHUDsForView:lockVC.view animated:YES];
                [UsefulUtil showAlertView:@"遇到网络问题，请稍候重试!"];
            }
        }];
        
    }];

}

#pragma mark - alert view delegate 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 1) {
        
        [self gesturePWD];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
